import machine
import time
import util  # 导入工具模块

# 初始化霍尔传感器引脚
hall_d22 = machine.Pin(22, machine.Pin.IN, machine.Pin.PULL_UP)
hall_d16 = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_UP)
hall_d17 = machine.Pin(17, machine.Pin.IN, machine.Pin.PULL_UP)

# 初始化电机控制引脚
motor_d19 = machine.Pin(19, machine.Pin.OUT)
motor_d18 = machine.Pin(18, machine.Pin.OUT)

# 初始化 NPN 型光电传感器引脚
photoelectric_d27 = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP)

# 抖动函数
def shake_motor(s):
    start_time = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start_time) < s*1000:  # 抖动 N秒
        motor_d18.off()
        motor_d19.on()
        time.sleep_ms(800)  # 逆时针转动 200 毫秒
        motor_d19.off()
        motor_d18.on()
        time.sleep_ms(800)  # 顺时针转动 200 毫秒

# 检测光电传感器信号并处理
def check_photoelectric(paused, last_d19_state, last_d18_state):
    if photoelectric_d27.value() == 0:  # 检测到猫，停止动作
        if not paused:
            last_d19_state = motor_d19.value()
            last_d18_state = motor_d18.value()
            motor_d19.off()
            motor_d18.off()
            print("检测到猫，电机停止转动")
            paused = True
    else:  # 猫离开，恢复动作
        if paused:
            motor_d19.value(last_d19_state)
            motor_d18.value(last_d18_state)
            if last_d19_state == 1:
                print("猫离开，电机逆时针转动")
            elif last_d18_state == 1:
                print("猫离开，电机顺时针转动")
            paused = False
    return paused, last_d19_state, last_d18_state

# 清理猫屎
def clean_up_cat_poop():
    # 新增：超时控制参数
    MAX_CLEAN_TIME = 40 * 1000  # 最大清理时间（毫秒），30秒
    start_time = time.ticks_ms()  # 开始时间
    pause_start = 0  # 暂停开始时间
    total_pause = 0  # 累计暂停时间（毫秒）

    # 先逆时针转
    motor_d19.on()
    motor_d18.off()
    print("电机逆时针转动")

    paused = False  # 用于标记是否暂停清理动作
    last_d19_state = motor_d19.value()
    last_d18_state = motor_d18.value()
    step = 0  # 用于记录当前需要触发的霍尔传感器步骤

    while True:
        # 新增：检查超时（扣除暂停时间）
        current_time = time.ticks_ms()
        elapsed = time.ticks_diff(current_time, start_time) - total_pause
        if elapsed > MAX_CLEAN_TIME:
            # 超时强制停止
            motor_d19.off()
            motor_d18.off()
            print(f"清理超时（{elapsed/1000}秒），强制停止")
            current_time = util.get_current_time()
            message = f"时间：{current_time},猫砂盆可能发生卡滞。"
            # 发送报警消息
            util.send_wechat_message(message)
            return  # 退出清理函数

        # 处理暂停逻辑（新增暂停计时）
        if paused and pause_start == 0:
            pause_start = current_time  # 记录暂停开始时间
        elif not paused and pause_start != 0:
            # 计算暂停时长并累加
            total_pause += time.ticks_diff(current_time, pause_start)
            pause_start = 0  # 重置暂停开始时间

        # 检测猫存在并处理暂停
        paused, last_d19_state, last_d18_state = check_photoelectric(paused, last_d19_state, last_d18_state)

        if not paused:
            if step == 0:
                # 检测 D22 霍尔信号
                if hall_d22.value() == 0:
                    time.sleep_ms(10)
                    if hall_d22.value() == 0:
                        print("检测到 D22 霍尔低电平信号，开始抖动")
                        shake_motor(4)
                        motor_d19.off()
                        motor_d18.on()
                        print("抖动结束，电机顺时针转动")
                        time.sleep(0.1)
                        step = 1
            elif step == 1:
                # 检测 D16 霍尔信号
                if hall_d16.value() == 0:
                    time.sleep_ms(10)
                    if hall_d16.value() == 0:
                        motor_d18.off()
                        motor_d19.on()
                        print("检测到 D16 霍尔低电平信号，电机逆时针转动")
                        time.sleep(0.1)
                        step = 2
            elif step == 2:
                # 检测 D17 霍尔信号
                if hall_d17.value() == 0:
                    time.sleep_ms(10)
                    if hall_d17.value() == 0:
                        motor_d19.off()
                        motor_d18.off()
                        print("检测到 D17 霍尔低电平信号，电机停止转动")
                        break  # 正常结束

        time.sleep_ms(20)

# 一键倒沙子
def pouring_sand():
    print("开始倒沙子")
    motor_d19.off()
    motor_d18.on()
    paused = False
    last_d19_state = motor_d19.value()
    last_d18_state = motor_d18.value()
    step = 0

    while True:
        paused, last_d19_state, last_d18_state = check_photoelectric(paused, last_d19_state, last_d18_state)

        if not paused:
            if step == 0:
                # 检测 D22 霍尔信号
                if hall_d22.value() == 0:
                    time.sleep_ms(10)
                    if hall_d22.value() == 0:
                        print("检测到 D22 霍尔低电平信号，开始抖动")
                        shake_motor(10)
                        motor_d18.off()
                        motor_d19.on()
                        print("抖动结束，继续倒沙子")
                        time.sleep(0.1)  # 短暂延迟，避免抖动
                        step = 1
            elif step == 1:
                # 检测 D17 霍尔信号
                if hall_d17.value() == 0:
                    time.sleep_ms(10)
                    if hall_d17.value() == 0:
                        motor_d19.off()
                        motor_d18.off()
                        print("检测到 D17 霍尔低电平信号,猫砂就位，电机停止转动")
                        break

        time.sleep_ms(20)


if __name__ == "__main__":
    clean_up_cat_poop()


